package com.rc.saas.mini.hlhtcec2.printer.operator;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rc.saas.mini.common.constant.HttpConstant;
import com.rc.saas.mini.hlhtcec2.config.HlhtBizPubFetchTool;
import com.rc.saas.mini.hlhtcec2.printer.HlhtPrintStrategy;
import com.rc.saas.mini.model.hlhtsk.HlhtskBizOperator;
import com.rc.saas.mini.model.hlhtsk.HlhtskBizTenant;
import com.rc.saas.mini.vo.cec.StdRequest;
import com.rc.saas.mini.vo.hlht.ext.XxQueryParkingPrintReq;
import com.rc.saas.mini.vo.hlht.ext.XxQueryParkingPrintResult;
import com.rc.saas.mini.vo.hlht.ext.XxQueryParkingPrintersReq;
import com.rc.saas.mini.vo.hlht.ext.XxQueryParkingPrintersResult;
import com.rc.saas.mini.vo.hlhtcec2.TokenResult;
import com.rc.saas.mini.vo.printer.QueryPrintReq;
import com.rc.saas.mini.vo.printer.QueryPrintResult;
import com.rc.saas.mini.vo.printer.StartPrintReq;
import com.rc.saas.mini.vo.printer.StartPrintResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * 星星充电
 * @author wangzhengwei
 * @create 2021/4/23
 */
public class HlhtPrinterXx implements HlhtPrintStrategy {
    private static Logger logger = LogManager.getLogger(HlhtPrinterXx.class);

    //加密时间戳格式
    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");


    private final String HLHT_OPERATORID = "313744932";
    private final String QUERY_PRINT_URL = "/query_parking_printers";   //查询小票机列表
    private final String QUERY_START_PRINT_URL = "/query_parking_print"; //打印订单信息

    @Override
    public QueryPrintResult query_print(QueryPrintReq request, TokenResult tokenResult, HlhtskBizOperator bizOperator, HlhtskBizTenant bizTenant) {
        //组装运营自己的VO
        XxQueryParkingPrintersReq queryParkingPrintersReq = new XxQueryParkingPrintersReq();
        queryParkingPrintersReq.setStartChargeSeq(request.getStartChargeSeq());

        //URL
        String URL = bizOperator.getHlhtUrl2() + QUERY_PRINT_URL;

        //默认返回值
        QueryPrintResult defaultResult = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            String enData = objectMapper.writeValueAsString(queryParkingPrintersReq);
            logger.info(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":query_print 回调报文:{}", enData);

            //使用运营商ID加密
            String retdata = HlhtBizPubFetchTool.genDDEncodeData2(bizOperator, enData);

            //使用我方ID签名
            String timeStamp = sdf.format(System.currentTimeMillis());

            //使用我方ID签名
            String sig = HlhtBizPubFetchTool.genDDSig2(bizOperator, retdata, timeStamp);

            StdRequest resp = genSuccessResp2(retdata, bizOperator, sig, timeStamp);

            String respData = objectMapper.writeValueAsString(resp);

            logger.info(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":query_print 开始推送给:{}", URL);
            return Request.Post(URL)
                    .addHeader("Content-Type", HttpConstant.CONTENT_TYPE_JSON)
                    .addHeader("Authorization", HttpConstant.AUTHORIZATION_PREFIX + tokenResult.getAccessToken())
                    .connectTimeout(3000)
                    .body(new StringEntity(respData))
                    .execute()
                    .handleResponse(new ResponseHandler<QueryPrintResult>() {
                        @Override
                        public QueryPrintResult handleResponse(HttpResponse httpResponse) throws IOException {
                            int code = httpResponse.getStatusLine().getStatusCode();
                            logger.info(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":query_print 发送:{},:{},:{}", request.getStartChargeSeq(), code, URL);

                            if (code == 200) {
                                HttpEntity entity = httpResponse.getEntity();
                                String result = EntityUtils.toString(entity, "UTF-8");
                                logger.info(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":query_print response,:{},:{}", result, URL);

                                if (StringUtils.isBlank(result)) {
                                    return defaultResult;
                                }

                                StdRequest hlhtResponse = JSON.parseObject(result, StdRequest.class);
                                if (hlhtResponse == null) {
                                    return defaultResult;
                                }

                                //根据对方ID对传来的信息进行签名校验
                                //boolean checkSig = PubFetchTool.checkSig2(tRequest, operatorID);
                                //if (!checkSig) {
                                //    return Integer.valueOf(0);
                                //}

                                //根据对方ID对合作方传来的信息进行解密
                                String deData = HlhtBizPubFetchTool.genDDDecodeData2(bizOperator, hlhtResponse.getData());
                                logger.info(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":query_print 返回明文:{},:{}", deData, URL);

                                XxQueryParkingPrintersResult operatorResult = JSON.parseObject(deData, XxQueryParkingPrintersResult.class);

                                //ObjectMapper objectMapper = new ObjectMapper();
                                //String enData = objectMapper.writeValueAsString(notifyStartChargeResult);
                                //logger.info("notification_start_charge_result 推送结果:{}", enData);

                                //将运营商的VO转为统一的QueryPrintResult
                                QueryPrintResult toResult = new QueryPrintResult();
                                toResult.setStartChargeSeq(request.getStartChargeSeq());

                                //取打印机编号
                                if (!CollectionUtils.isEmpty(operatorResult.getPrinterInfos())) {
                                    toResult.setPrinterID(operatorResult.getPrinterInfos().get(0).getPrinterID());
                                }

                                toResult.setSuccStat(operatorResult.getSuccStat());
                                toResult.setFailReason(operatorResult.getFailReasonCode());
                                toResult.setFailReasonMsg(operatorResult.getFailReasonMsg());

                                return toResult;
                            } else {
                                return defaultResult;
                            }
                        }
                    });

        } catch (Exception e) {
            logger.error(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":query_print 报错", e);
            logger.error(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":query_print 报错", URL);
        }

        return null;
    }

    @Override
    public StartPrintResult query_start_print(StartPrintReq request, TokenResult tokenResult, HlhtskBizOperator bizOperator, HlhtskBizTenant bizTenant) {
        //组装运营自己的VO
        XxQueryParkingPrintReq queryParkingPrintReq = new XxQueryParkingPrintReq();
        queryParkingPrintReq.setPrinterID(request.getPrinterID());
        queryParkingPrintReq.setStartChargeSeq(request.getStartChargeSeq());

        //URL
        String URL = bizOperator.getHlhtUrl2() + QUERY_START_PRINT_URL;

        //默认返回值
        StartPrintResult defaultResult = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            String enData = objectMapper.writeValueAsString(queryParkingPrintReq);
            logger.info(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":query_start_print 回调报文:{}", enData);

            //使用运营商ID加密
            String retdata = HlhtBizPubFetchTool.genDDEncodeData2(bizOperator, enData);

            //使用我方ID签名
            String timeStamp = sdf.format(System.currentTimeMillis());

            //使用我方ID签名
            String sig = HlhtBizPubFetchTool.genDDSig2(bizOperator, retdata, timeStamp);

            StdRequest resp = genSuccessResp2(retdata, bizOperator, sig, timeStamp);

            String respData = objectMapper.writeValueAsString(resp);

            logger.info(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":query_start_print 开始推送给:{}", URL);
            return Request.Post(URL)
                    .addHeader("Content-Type", HttpConstant.CONTENT_TYPE_JSON)
                    .addHeader("Authorization", HttpConstant.AUTHORIZATION_PREFIX + tokenResult.getAccessToken())
                    .connectTimeout(3000)
                    .body(new StringEntity(respData))
                    .execute()
                    .handleResponse(new ResponseHandler<StartPrintResult>() {
                        @Override
                        public StartPrintResult handleResponse(HttpResponse httpResponse) throws IOException {
                            int code = httpResponse.getStatusLine().getStatusCode();
                            logger.info(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":query_start_print 发送:{},:{},:{}", request.getStartChargeSeq(), code, URL);

                            if (code == 200) {
                                HttpEntity entity = httpResponse.getEntity();
                                String result = EntityUtils.toString(entity, "UTF-8");
                                logger.info(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":query_start_print response,:{},:{}", result, URL);

                                if (StringUtils.isBlank(result)) {
                                    return defaultResult;
                                }

                                StdRequest hlhtResponse = JSON.parseObject(result, StdRequest.class);
                                if (hlhtResponse == null) {
                                    return defaultResult;
                                }

                                //根据对方ID对传来的信息进行签名校验
                                //boolean checkSig = PubFetchTool.checkSig2(tRequest, operatorID);
                                //if (!checkSig) {
                                //    return Integer.valueOf(0);
                                //}

                                //根据对方ID对合作方传来的信息进行解密
                                String deData = HlhtBizPubFetchTool.genDDDecodeData2(bizOperator, hlhtResponse.getData());
                                logger.info(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":query_start_print 返回明文:{},:{}", deData, URL);

                                XxQueryParkingPrintResult operatorResult = JSON.parseObject(deData, XxQueryParkingPrintResult.class);

                                //ObjectMapper objectMapper = new ObjectMapper();
                                //String enData = objectMapper.writeValueAsString(notifyStartChargeResult);
                                //logger.info("notification_start_charge_result 推送结果:{}", enData);

                                //将运营商的VO转为统一的QueryPrintResult
                                StartPrintResult toResult = new StartPrintResult();
                                toResult.setStartChargeSeq(request.getStartChargeSeq());

                                toResult.setSuccStat(operatorResult.getSuccStat());
                                toResult.setFailReason(operatorResult.getFailReasonCode());
                                toResult.setFailReasonMsg(operatorResult.getFailReasonMsg());

                                return toResult;
                            } else {
                                return defaultResult;
                            }
                        }
                    });

        } catch (Exception e) {
            logger.error(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":query_start_print 报错", e);
            logger.error(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":query_start_print 报错", URL);
        }

        return null;
    }

    @Override
    public String getHlhtOperatorId() {
        return HLHT_OPERATORID;
    }

    private StdRequest genSuccessResp2(String data, HlhtskBizOperator bizOperator, String sig, String timeStamp) {
        StdRequest request = new StdRequest();
        request.setTimeStamp(timeStamp);

        request.setSig(sig);
        request.setData(data);
        if (StringUtils.isBlank(bizOperator.getLicenseTenantCode())) {
            request.setOperatorID(bizOperator.getTenantCode());
        } else {
            request.setOperatorID(bizOperator.getLicenseTenantCode());
        }
        request.setSeq("0001");
        return request;
    }


}
